<template>
  <div>
    <el-card v-permission="['maintain:info:repair']" body-style="min-height: 86vh">
      <el-form ref="formAddRef" label-width="170" :model="formAdd" :rules="rulesAdd">
        <el-row :gutter="20">
          <template v-for="(item, index) in formList" :key="index">
            <el-col v-if="item.type === 'input'" :span="8">
              <el-form-item :label="item.label" :prop="item.prop">
                <el-input v-model="formAdd[item.prop]" :disabled="handleIsDiabled(item.prop)"
                  :placeholder="item.placeholder" />
              </el-form-item>
            </el-col>
            <el-col v-else-if="item.type === 'select'" :span="8">
              <el-form-item :label="item.label" :prop="item.prop">
                <el-select v-model="formAdd[item.prop]" :disabled="handleIsDiabled(item.prop)"
                  :placeholder="item.placeholder" filterable>
                  <el-option v-for="(item1, index1) in item.options" :key="index1" :label="item1.label"
                    :value="item1.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-else-if="item.type === 'time'" :span="8">
              <el-form-item :label="item.label" :prop="item.prop">
                <el-date-picker v-model="formAdd[item.prop]" type="date" :disabled="handleIsDiabled(item.prop)"
                  :placeholder="item.placeholder" value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col v-else-if="item.type === 'textarea'" :span="12">
              <el-form-item :label="item.label" :prop="item.prop">
                <el-input v-model="formAdd[item.prop]" type="textarea" :disabled="handleIsDiabled(item.prop)"
                  :placeholder="item.placeholder"></el-input>
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
      <div class="flex justify-center">
        <el-button type="primary" @click="handleSaveInfo">保存</el-button>
      </div>
    </el-card>
    <el-card v-permission="['maintain:info:admin']" body-style="min-height: 86vh">
      <el-form :model="searchForm" label-width="120">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="企业编号">
              <el-input v-model="searchForm.companyNo" placeholder="请输入企业编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业名称">
              <el-input v-model="searchForm.companyName" placeholder="请输入企业名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="经营业务类别">
              <el-select v-model="searchForm.businessType" placeholder="请选择经营业务类别"><el-option
                  v-for="item in companyManageTypeList" :key="item.label" :label="item.label"
                  :value="item.value"></el-option></el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="经营状态">
              <el-select v-model="searchForm.runStatus" placeholder="请选择经营状态"><el-option
                  v-for="item in companyManageStatusList" :key="item.label" :label="item.label"
                  :value="item.value"></el-option></el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备案编号">
              <el-input v-model="searchForm.filingNo" placeholder="请输入备案编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="区县/管辖机构">
              <el-select v-model="searchForm.areaCode" placeholder="请选择区县">
                <el-option v-for="item in areaList" :key="item.areaCode" :label="item.area" :value="item.areaCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button @click="handleRestSearch()">重置</el-button>
              <el-button type="primary" @click="handleGetTableList()">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider />
      <!-- 新增、筛选按钮 -->
      <div class="flex justify-end">
        <div>
          <el-button circle @click="handleGetTableList()">
            <template #icon><el-icon>
                <Refresh />
              </el-icon></template>
          </el-button>
        </div>
      </div>
      <el-table :data="tableData">
        <el-table-column prop="companyNo" label="企业编号" />
        <el-table-column prop="companyName" label="企业名称" />
        <el-table-column prop="city" label="行政区划市" />
        <el-table-column prop="area" label="区县/管辖机构" />
        <el-table-column prop="businessType" label="经营业务类别" />
        <el-table-column prop="runStatus" label="经营状态" />
        <el-table-column prop="filingNo" label="备案编号" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="flex justify-center mt-2" background layout="total,prev, pager, next"
        :current-page="currentPage" :page-size="limit" :total="total" @current-change="handleGetTableList" />
      <form-dialog ref="formDrawerRef" width="98%" top="1vh" @submit="handleSubmit">
        <div class="dialog-body">
          <el-form ref="formRef" label-width="170" :model="form" :rules="rules">
            <el-row :gutter="20">
              <template v-for="(item, index) in formList" :key="index">
                <el-col v-if="item.type === 'input'" :span="8">
                  <el-form-item :label="item.label" :prop="item.prop">
                    <el-input v-model="form[item.prop]" :disabled="handleIsDiabled(item.prop)"
                      :placeholder="item.placeholder" />
                  </el-form-item>
                </el-col>
                <el-col v-else-if="item.type === 'select'" :span="8">
                  <el-form-item :label="item.label" :prop="item.prop">
                    <el-select v-model="form[item.prop]" :disabled="handleIsDiabled(item.prop)"
                      :placeholder="item.placeholder">
                      <el-option v-for="(item1, index1) in item.options" :key="index1" :label="item1.label"
                        :value="item1.value"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col v-else-if="item.type === 'time'" :span="8">
                  <el-form-item :label="item.label" :prop="item.prop">
                    <el-date-picker v-model="form[item.prop]" type="date" :placeholder="item.placeholder"
                      value-format="YYYY-MM-DD HH:mm:ss" :disabled="handleIsDiabled(item.prop)"
                      style="width: 100%"></el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col v-else-if="item.type === 'textarea'" :span="12">
                  <el-form-item :label="item.label" :prop="item.prop">
                    <el-input v-model="form[item.prop]" type="textarea" :disabled="handleIsDiabled(item.prop)"
                      :placeholder="item.placeholder"></el-input>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </el-form>
        </div>
      </form-dialog>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, watch, watchEffect } from "vue";
import usePermission from "@/hooks/usePermission";
import { useInitTable, useInitForm } from "@/hooks/useCommon";
import FormDialog from "@/components/FormDialog.vue";
import { toast } from "@/utils/index";
import { companyManageTypeList, companyEconomyList, companyManageStatusList } from "@/enum/index";
import {
  getOneRepairStoreInfoApi,
  editEnterpriseInfoApi,
  getAllRepairStoreInfoApi
} from "@/api/maintain";
import { getAreaListApi } from '@/api/user'

// 权限
const { hasPermission } = usePermission();

const isAdmin = computed(() => {
  return hasPermission("maintain:info:admin");
});
// 管理员表格
const { searchForm, tableData, currentPage, limit, total, handleRestSearch, handleGetTableList } =
  useInitTable({
    searchForm: {
      companyNo: "",
      companyName: "",
      businessType: "",
      runStatus: "",
      filingNo: "",
      areaCode: ""
    },
    getTableList: getAllRepairStoreInfoApi,
    isNotRefresh: true
  });
const formList = ref([
  {
    label: "企业编号",
    prop: "companyNo",
    type: "input",
    placeholder: "请输入维修项目"
  },
  {
    label: "企业名称",
    prop: "companyName",
    type: "input",
    placeholder: "请输入维修项目"
  },
  {
    label: "行政区划/市",
    prop: "cityCode",
    type: "select",
    placeholder: "请选择行政区划/市",
    options: []
  },
  {
    label: "备案编号",
    prop: "filingNo",
    type: "input",
    placeholder: "请输入备案编号"
  },
  {
    label: "企业地址",
    prop: "companyAddress",
    type: "input",
    placeholder: "请输入企业地址"
  },
  {
    label: "区县/管辖机构",
    prop: "areaCode",
    type: "select",
    placeholder: "请选择区县/管辖机构",
    options: []
  },
  {
    label: "组织机构代码",
    prop: "organizingCode",
    type: "input",
    placeholder: "请输入组织机构代码"
  },
  {
    label: "统一社会信用代码",
    prop: "unifiedSocialCreditIdentifier",
    type: "input",
    placeholder: "请输入统一社会信用代码"
  },
  {
    label: "道路经营许可证失效日期",
    prop: "businessLicenseFailureTime",
    type: "time",
    placeholder: "请选择道路经营许可证失效日期"
  },
  {
    label: "企业经营业务类别",
    prop: "businessType",
    type: "select",
    placeholder: "请选择企业经营业务类别",
    options: []
  },
  {
    label: "道路经营许可证发证日期",
    prop: "businessLicenseSendTime",
    type: "time",
    placeholder: "请选择道路经营许可证发证日期"
  },
  {
    label: "企业邮箱",
    prop: "companyEmail",
    type: "input",
    placeholder: "请输入企业邮箱"
  },
  {
    label: "企业经营状态",
    prop: "runStatus",
    type: "select",
    placeholder: "请选择企业经营状",
    options: []
  },
  {
    label: "企业经济类型",
    prop: "ecoType",
    type: "select",
    placeholder: "请选择企业经济类型",
    options: []
  },
  {
    label: "邮政编码",
    prop: "postalCode",
    type: "input",
    placeholder: "请输入邮政编码"
  },
  {
    label: "联系人姓名",
    prop: "contactName",
    type: "input",
    placeholder: "请输入联系人姓名"
  },
  {
    label: "企业经营范围",
    prop: "businessScope",
    type: "input",
    placeholder: "请输入企业经营范围"
  },
  {
    label: "上级企业名称",
    prop: "higherCompany",
    type: "input",
    placeholder: "请输入上级企业名称"
  },
  {
    label: "联系人联系方式",
    prop: "contactPhone",
    type: "input",
    placeholder: "请输入联系人联系方式"
  },
  {
    label: "联网厂商",
    prop: "networkingVendors",
    type: "input",
    placeholder: "请输入联网厂商"
  },
  {
    label: "上级企业经营许可证号",
    prop: "higherCompanyBusinessLicensNo",
    type: "input",
    placeholder: "请输入上级企业经营许可证号"
  },
  {
    label: "负责人姓名",
    prop: "principalName",
    type: "input",
    placeholder: "请输入负责人姓名"
  },
  {
    label: "企业类型",
    prop: "companyType",
    type: "select",
    placeholder: "请选择企业类型",
    options: [
      {
        label: "4S店或特约维修站",
        value: 1
      },
      {
        label: "综合维修企业",
        value: 2
      },
      {
        label: "连锁或集团经营企业",
        value: 3
      }
    ]
  },
  {
    label: "是否为 M 站",
    prop: "isM",
    type: "select",
    placeholder: "请选择是否为 M 站",
    options: [
      {
        label: "是",
        value: 1
      },
      {
        label: "否",
        value: 0
      }
    ]
  },
  {
    label: "负责人联系方式",
    prop: "principalPhone",
    type: "input",
    placeholder: "请输入负责人联系方式"
  },
  {
    label: "诚信考核等级",
    prop: "integrityAssessmentLevel",
    type: "input",
    placeholder: "请输入诚信考核等级"
  },
  {
    label: "备注",
    prop: "remark",
    type: "input",
    placeholder: "请输入备注"
  },
  {
    label: "电话号码",
    prop: "phone",
    type: "input",
    placeholder: "请输入电话号码"
  },
  {
    label: "诚信考核总分",
    prop: "integrityAssessmentScore",
    type: "input",
    placeholder: "请输入诚信考核总分"
  },
  {
    label: "企业概述",
    prop: "companySummarize",
    type: "textarea",
    placeholder: "请输入企业概述"
  },
  {
    label: "优势服务",
    prop: "server",
    type: "textarea",
    placeholder: "请输入优势服务"
  },
  {
    label: "质保信息",
    prop: "warrantyInfo",
    type: "textarea",
    placeholder: "请输入质保信息"
  },
  {
    label: "近期活动",
    prop: "active",
    type: "textarea",
    placeholder: "请输入近期活动"
  },
  {
    label: "主修品牌",
    prop: "majorBrand",
    type: "textarea",
    placeholder: "请输入主修品牌"
  }
]);
const formAddRef = ref(null);
const formAdd: any = ref({
  id: "",
  companyNo: "",
  companyName: "",
  cityCode: "",
  filingNo: "",
  companyAddress: "",
  areaCode: "",
  organizingCode: "",
  unifiedSocialCreditIdentifier: "",
  businessLicenseFailureTime: "",
  businessType: "",
  businessLicenseSendTime: "",
  companyEmail: "",
  runStatus: "",
  ecoType: "",
  postalCode: "",
  contactName: "",
  businessScope: "",
  higherCompany: "",
  contactPhone: "",
  networkingVendors: "",
  higherCompanyBusinessLicensNo: "",
  principalName: "",
  companyType: "",
  isM: "",
  principalPhone: "",
  integrityAssessmentLevel: "",
  remark: "",
  phone: "",
  integrityAssessmentScore: "",
  companySummarize: "",
  server: "",
  warrantyInfo: "",
  active: "",
  majorBrand: ""
});
const rulesAdd = ref({});
let { formDrawerRef, formRef, rules, form, handleEdit, handleSubmit } = useInitForm({
  form: {
    id: "",
    companyNo: "",
    companyName: "",
    cityCode: "",
    filingNo: "",
    companyAddress: "",
    areaCode: "",
    organizingCode: "",
    unifiedSocialCreditIdentifier: "",
    businessLicenseFailureTime: "",
    businessType: "",
    businessLicenseSendTime: "",
    companyEmail: "",
    runStatus: "",
    ecoType: "",
    postalCode: "",
    contactName: "",
    businessScope: "",
    higherCompany: "",
    contactPhone: "",
    networkingVendors: "",
    higherCompanyBusinessLicensNo: "",
    principalName: "",
    companyType: "",
    isM: "",
    principalPhone: "",
    integrityAssessmentLevel: "",
    remark: "",
    phone: "",
    integrityAssessmentScore: "",
    companySummarize: "",
    server: "",
    warrantyInfo: "",
    active: "",
    majorBrand: ""
  },
  rules: rulesAdd.value
});
const handleRepairRules = () => {
  const isAdmin = hasPermission("maintain:info:admin");
  let curItem: any = {
    unifiedSocialCreditIdentifier: [
      { required: true, message: "请输入统一社会信用代码", trigger: "blur" }
    ],
    companyEmail: [
      { required: true, message: "请输入公司邮箱", trigger: "blur" },
      { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
    ],
    contactName: [{ required: true, message: "请输入联系人姓名", trigger: "blur" }],
    contactPhone: [{ required: true, message: "请输入联系人联系方式", trigger: "blur" }],
    principalName: [{ required: true, message: "请输入负责人姓名", trigger: "blur" }],
    companyType: [{ required: true, message: "请选择企业类型", trigger: "blur" }],
    principalPhone: [{ required: true, message: "请输入负责人联系方式", trigger: "blur" }],
    phone: [{ required: true, message: "请输入公司电话", trigger: "blur" }]
  };
  if (isAdmin) {
    curItem = {
      ...curItem,
      companyNo: [{ required: true, message: "请输入企业编号", trigger: "blur" }],
      companyName: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
      cityCode: [{ required: true, message: "请选择行政区划/市", trigger: "blur" }],
      filingNo: [{ required: true, message: "请输入备案编号", trigger: "blur" }],
      businessType: [{ required: true, message: "请选择企业经营业务类别", trigger: "blur" }],
      runStatus: [{ required: true, message: "请选择企业经营状态", trigger: "change" }]
    };
  }
  rulesAdd.value = curItem;
};

// 获取当前修理厂信息
const handleGetRepairStoreInfo = async () => {
  if (isAdmin.value) return false;
  const res = await getOneRepairStoreInfoApi();
  formAdd.value = res;
};

// 管理员-获取所有修理厂列表
const handleGetAllRepairStoreList = () => {
  if (isAdmin.value) {
    handleGetTableList();
  }
};

// 处理数据-添加下拉选项
const handleFilterData = () => {
  formList.value.forEach((item: any) => {
    if (item.prop === "businessType") {
      item.options = companyManageTypeList;
    } else if (item.prop === "runStatus") {
      item.options = companyManageStatusList;
    } else if (item.prop === "ecoType") {
      item.options = companyEconomyList;
    }
  });
};

// 是否禁用
const handleIsDiabled = (val: string) => {
  let disabledList = [
    "companyNo",
    "companyName",
    "isM",
    "integrityAssessmentLevel",
    "integrityAssessmentScore"
  ];
  if (!isAdmin.value) {
    const curItem = ["cityCode", "areaCode", "filingNo"];
    disabledList.push(...curItem);
  }
  return disabledList.includes(val);
};

// 保存
const handleSaveInfo = () => {
  formAddRef.value &&
    (formAddRef.value as any).validate(async (valid: any) => {
      if (valid) {
        const res = await editEnterpriseInfoApi(formAdd.value);
        if (res) {
          toast("保存成功");
          handleGetRepairStoreInfo();
        }
      }
    });
};

watch(
  () => rulesAdd,
  () => {
    handleRepairRules();
  },
  {
    immediate: true
  }
);
watchEffect(() => {
  rules = rulesAdd.value;
});

const areaList = ref(new Array())
const getAreaList = async () => {
  const res = await getAreaListApi() as any
  areaList.value = res
}

onMounted(() => {
  handleGetRepairStoreInfo();
  handleGetAllRepairStoreList();
  handleFilterData();
  getAreaList()
});

</script>
<style scoped lang="scss">
.dialog-body {
  height: calc(100vh - 170px);
  overflow-y: auto;
}
</style>
